from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views.decorators.clickjacking import xframe_options_sameorigin
from rest_framework.views import APIView
from rest_framework.response import Response
from blog.models import Article, Classify, User, Comment
from faker import Faker

from blog.utils.jwt_auth import get_user_id
from util.util import generate_file_name
from django.views.decorators.csrf import csrf_exempt


class ListArticleView(APIView):
    def get(self, request, *args, **kwargs):
        try:
            page = request.GET.get('page')
            limit = request.GET.get('limit')
            title = request.GET.get('title')
            id = request.GET.get('id')
            classify = request.GET.get('classify')
            article = Article.objects.filter(status=1)
            if id:
                article = article.filter(user_id=id)
            if title and title != 'null':
                article = article.filter(title__contains=title)
            if classify and classify != 'null':
                article = article.filter(classify__name__contains=classify)
            if len(article) == 0:
                return Response({'status': 200, 'msg': '获取成功', 'count': 0, 'data': article})
            ptr = Paginator(article, limit)
            article_list = []
            for item in ptr.page(page):
                article_list.append(
                    {'id': item.id, 'content': item.content[0:50], 'title': item.title, 'date': item.create_time,
                     'category': item.classify.name})
            return Response({
                'status': 200,
                'msg': '获取成功',
                'count': ptr.count,
                'data': article_list
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class GetOneArticle(APIView):
    def get(self, request, *args, **kwargs):
        try:
            id = request.GET.get('id')
            article = Article.objects.filter(status=1, id=id).first()
            if not article:
                return Response({'status': 204, 'msg': '文章不存在'})
            article.view_num += 1
            article.save()
            comment_list = []
            count = 0
            for item in article.comment_set.all():
                if item.status == 0:
                    continue
                count += 1
                data = {'id': item.id, 'user': item.user.name, 'photo': item.user.photo, 'date': item.create_time,
                        'content': item.content}
                comment_list.append(data)
            return Response({
                'status': 200,
                'msg': '获取成功',
                'data': {'id': article.id, 'title': article.title, 'content': article.content,
                         "date": article.create_time, "view": article.view_num, 'classify': article.classify.id,
                         'count': count, 'comment': comment_list}
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class DelArticleViwe(APIView):
    def post(self, request, *args, **kwargs):
        try:
            id = request.data.get('id')
            article = Article.objects.filter(status=1, id=id).first()
            if not article:
                return Response({'status': 204, 'msg': '文章不存在'})
            article.status = 0
            article.save()
            return Response({
                'status': 200,
                'msg': '删除成功',
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class ListClassify(APIView):
    def get(self, request, *args, **kwargs):
        try:
            page = request.GET.get('page')
            limit = request.GET.get('limit')
            name = request.GET.get('name')
            classify = []
            if name is None:
                classify = Classify.objects.filter(status=1)
            else:
                classify = Classify.objects.filter(status=1, name__contains=name)
            if len(classify) == 0:
                return Response({'status': 200, 'msg': '获取成功', 'count': 0, 'data': classify})
            # print(list(classify.values()))
            ptr = Paginator(classify, limit)
            classify_list = []
            for item in ptr.page(page):
                classify_list.append({'id': item.id, 'name': item.name, 'describe': item.describe})
            return Response({
                'status': 200,
                'msg': '获取成功',
                'count': ptr.count,
                'data': classify_list
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class ListAllClassify(APIView):
    def get(self, request, *args, **kwargs):
        try:
            classify = Classify.objects.filter(status=1)
            classify_list = []
            for item in classify:
                classify_list.append({'id': item.id, 'name': item.name, 'describe': item.describe})
            return Response({
                'status': 200,
                'msg': '获取成功',
                'data': classify_list
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class DelClassifyView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            id = request.data.get('id')
            classify = Classify.objects.filter(status=1, id=id).first()
            if not classify:
                return Response({'status': 204, 'msg': '分类不存在'})
            classify.status = 0
            classify.save()
            return Response({
                'status': 200,
                'msg': '删除成功',
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class CreateView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')
            user_id = get_user_id(token)
            title = request.data.get('title')
            content = request.data.get('content')
            classify_id = request.data.get('classify')
            article = Article()
            article.user = User.objects.filter(status=1, id=user_id).first()
            article.title = title
            article.content = content
            article.classify = Classify.objects.filter(status=1, id=classify_id).first()
            article.save()
            return Response({
                'status': 200,
                'msg': '创建成功'
            })
        except Exception as e:
            print(e.args)
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class TopView(APIView):
    def get(self, request, *args, **kwargs):
        try:
            article_list = Article.objects.filter(status=1).order_by('-view_num')[0:2]
            top_list = []
            for article in article_list:
                data = {'id': article.id, 'title': article.title, 'date': article.create_time,
                        'content': article.content[0:30], 'view': article.view_num,
                        'author': article.user.name, 'photo': article.user.photo}
                top_list.append(data)
            article_list = Article.objects.filter(status=1).order_by('-id')[0:2]
            new_list = []
            for article in article_list:
                data = {'id': article.id, 'title': article.title, 'date': article.create_time,
                        'content': article.content[0:30], 'view': article.view_num,
                        'author': article.user.name, 'photo': article.user.photo}
                new_list.append(data)
            data = {
                'top': top_list,
                'newest': new_list
            }
            return Response({
                'status': 200,
                'msg': '获取成功',
                'data': data
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class GetCount(APIView):
    def get(self, request, *args, **kwargs):
        try:
            id = request.GET.get('id')
            title = request.GET.get('title')
            classify = request.GET.get('classify')
            article = Article.objects.filter(status=1)
            if id:
                article = article.filter(user_id=id)
            if title and title != 'null':
                article = article.filter(title__contains=title)
            if classify and classify != 'null':
                article = article.filter(classify__name__contains=classify)
            count = len(article)
            return Response({
                'status': 200,
                'msg': '获取成功',
                'data': {
                    'count': count
                }
            })
            pass
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class EditView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            id = request.data.get('id')
            title = request.data.get('title')
            content = request.data.get('content')
            classify = request.data.get('classify')
            article = Article.objects.filter(status=1, id=id).first()
            if article is None:
                return Response({'status': 204, 'msg': '文章不存在'})
            print(title)
            article.title = title
            article.content = content
            article.classify = Classify.objects.filter(status=1, id=classify).first()
            article.save()
            return Response({
                'status': 200,
                'msg': '修改成功',
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


# class GetArticleView(APIView):
#     def post(self, request, *args, **kwargs):
#         try:
#             page = request.GET.get('page')
#             limit = request.GET.get('limit')
#             title = request.GET.get('title')
#             article = []
#             if title is None:
#                 article = Article.objects.filter(status=1)
#             else:
#                 article = Article.objects.filter(status=1, title__contains=title)
#             if len(article) == 0:
#                 return Response({'status': 200, 'msg': '获取成功', 'count': 0, 'data': article})
#             ptr = Paginator(article, limit)
#             article_list = []
#             for item in ptr.page(page):
#                 article_list.append(
#                     {'id': item.id, 'title': item.title, 'date': item.create_time, 'category': item.classify.name})
#             return Response({
#                 'status': 200,
#                 'msg': '获取成功',
#                 'count': ptr.count,
#                 'data': article_list
#             })
#         except Exception as e:
#             return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


@csrf_exempt
def upload_image(request):
    data = {}
    try:
        image = request.FILES.get('editormd-image-file', None)
        name = generate_file_name() + '.' + image.name.split('.')[-1]
        import os
        from django.conf import settings
        filepath = os.path.join('static/upload', name)
        f = open(filepath, 'wb')
        for i in image.chunks():
            f.write(i)
        f.close()
        data['success'] = 1
        data['message'] = '提示的信息，上传成功或上传失败及错误信息等。'
        data['url'] = '/' + 'static/upload/' + name
    except Exception as e:
        data['success'] = 0
        data['message'] = e.args
    response = JsonResponse(data, json_dumps_params={'ensure_ascii': False})
    return response


@csrf_exempt
def upload_photo(request):
    data = {}
    try:

        file = request.FILES.get('file')
        file.name = generate_file_name() + '.' + file.name.split('.')[-1]
        import os
        from django.conf import settings
        filepath = os.path.join('static/upload', file.name)
        f = open(filepath, 'wb')
        for i in file.chunks():
            f.write(i)
        f.close()
        data['code'] = 0
        data['message'] = 'success'
        content = {'src': '/' + 'static/upload/' + file.name, 'title': file.name}
        data['data'] = content
    except Exception as e:
        print(e.args)
        data['code'] = 404
        data['message'] = e.args
    response = JsonResponse(data, json_dumps_params={'ensure_ascii': False})
    return response
